<?php
class IndexController extends Zendvn_Controller_Action{
	private $_paning = array('rowCount' => 9, 'pageRange' => 5);
	public function init(){
		parent::init();		
		$this->_templateObj->setPath(TEMPLATE_PATH . '/public/default');		
		$this->_templateObj->load();	
		
		/*====================================================
		 * Load Zendvn Translate for Controller
		 *====================================================*/
		$this->_langObj->setLangFile(array('validate.tmx'));		
		Zend_Registry::set('Zend_Translate',$this->_langObj->generate());
		
		/*====================================================
		 * Thiet lap gia tri cho phan phan trang cua controlle
		 *====================================================*/
		$pageNumber = $this->_request->getParam('page',1);
		$this->_paning['page'] = $pageNumber;
		$this->_arrParam['panigator'] = $this->_paning;
		
		/*====================================================
		 * Thiet lap duong dan chua file upload
		 *====================================================*/
		$this->view->addScriptPath(TEMPLATE_PATH . '/public/default');
		$this->view->arrParam = $this->_arrParam;
		$this->view->headLink()->appendStylesheet(PUBLIC_URL."/css/jquery.Jcrop.css",'screen');
		$this->view->headScript()->appendFile(PUBLIC_URL."/js/jquery.Jcrop.js",'text/javascript');
		
		
		
		
		/*========================================
		 * Set meta title - keywords - description
		*========================================*/
		$siteConfig = new Zendvn_Model_Table_SiteConfig();
		$siteConfig = $siteConfig->getItem(array('id' => 1));
		$title = Zendvn_Filter_Filter::filterContent($siteConfig['site_name'], 'filter');
		$option['keywords'] = Zendvn_Filter_Filter::filterContent($siteConfig['html_keyword'], 'filter');
		
		$option['description'] 	= Zendvn_Filter_Filter::filterContent($siteConfig['html_description'], 'filter');
		
		$this->setTitle($title, $option);
	}
	
	public function indexAction(){
		$this->view->headLink()->appendStylesheet(TEMPLATE_URL . '/public/default/css/nivo-slider.css','screen');
		$this->view->headScript()->appendFile(TEMPLATE_URL . '/public/default/js/jquery.nivo.slider.pack.js','text/javascript');
		
		$tblProductCategory = new Zendvn_Model_Table_ProductCategories();
		$this->view->Items = $tblProductCategory->itemInSelect($this->_arrParam, array('task' => 'cat-index'));
	}
	
	public function productCategoryAction(){
		/*==============================
		 * Category info
		 *==============================*/
		$tblCategory = new Zendvn_Model_Table_ProductCategories();
		$this->view->categoryInfo = $tblCategory->getItem($this->_arrParam);
		
		/*==============================
		 * List product of category
		 *==============================*/
		$tblItem = new Zendvn_Model_Table_Product();
		$this->view->Items = $tblItem->listItem($this->_arrParam, array('task' => 'list-category'));
		
		$totalItem = $tblItem->totalItem($this->_arrParam);
			
		$panigator = Zendvn_Paginator::create($this->_arrParam['panigator'],$totalItem);
		$this->view->panigator = $panigator;
		
		
		/*========================================
		 * Set meta title - keywords - description
		 *========================================*/
		$title = Zendvn_Filter_Filter::filterContent($this->view->categoryInfo['name'], 'filter');
		$option['keywords'] = Zendvn_Filter_Filter::filterContent($this->view->categoryInfo['html_keyword'], 'filter');
		
		$html_description 	= Zendvn_Filter_Filter::filterContent($this->view->categoryInfo['html_descript'], 'filter');
		$article_content 	= Zendvn_Filter_Filter::filterContent(trim(strip_tags($this->view->categoryInfo['content'])), 'filter');
		$article_content 	= Zendvn_Filter_Filter::shortString($article_content, 200);
		
		$description		= empty($html_description)?$article_content:$html_description;
		
		$option['description'] = $description;
		$this->setTitle($title, $option);
	}
	
	public function newProductAction(){
		/*==============================
		 * List product of category
		*==============================*/
		$tblItem = new Zendvn_Model_Table_Product();
		$this->view->Items = $tblItem->listItem($this->_arrParam, array('task' => 'new-product'));
	
		$totalItem = $tblItem->totalItem($this->_arrParam);
			
		$panigator = Zendvn_Paginator::create($this->_arrParam['panigator'],$totalItem);
		$this->view->panigator = $panigator;
	
		/*========================================
		 * Set meta title - keywords - description
		 *========================================*/
		$title = 'Sản phẩm mới';
		$this->setTitle($title);
		
		$this->view->headTitle = $title;
		$this->_helper->viewRenderer('product-category');
	}
	
	public function specialProductAction(){
		/*==============================
		 * List product of category
		*==============================*/
		$tblItem = new Zendvn_Model_Table_Product();
		$this->view->Items = $tblItem->listItem($this->_arrParam, array('task' => 'special-product'));
	
		$totalItem = $tblItem->totalItem($this->_arrParam);
			
		$panigator = Zendvn_Paginator::create($this->_arrParam['panigator'],$totalItem);
		$this->view->panigator = $panigator;
	
		/*========================================
		 * Set meta title - keywords - description
		*========================================*/
		$title = 'Sản phẩm đặc biệt';
		$this->setTitle($title);
		
		$this->view->headTitle = $title;
		$this->_helper->viewRenderer('product-category');
	}
	
	public function allProductAction(){
		/*==============================
		 * List product of category
		*==============================*/
		$tblItem = new Zendvn_Model_Table_Product();
		$this->view->Items = $tblItem->listItem($this->_arrParam, array('task' => 'all-product'));
	
		$totalItem = $tblItem->totalItem($this->_arrParam);
			
		$panigator = Zendvn_Paginator::create($this->_arrParam['panigator'],$totalItem);
		$this->view->panigator = $panigator;
	
		/*========================================
		 * Set meta title - keywords - description
		*========================================*/
		$title = 'Danh sách sản phẩm';
		$this->setTitle($title);
		
		$this->view->headTitle = $title;
		$this->_helper->viewRenderer('product-category');
	}
	
	public function productDetailAction(){
		$tblSize 					= new Zendvn_Model_Table_ProductSize();
		$this->view->slbSize 		= $tblSize->itemInSelect($this->_arrParam, array('task' => 'get-select'));
		
		$tblColor 					= new Zendvn_Model_Table_ProductColor();
		$this->view->slbColor 		= $tblColor->itemInSelect($this->_arrParam, array('task' => 'get-select'));
		
		$tblItem 					= new Zendvn_Model_Table_Product();
		$this->view->Item 			= $tblItem->getItem($this->_arrParam, array('task' => 'info'));
		
		/*========================================
		 * Set meta title - keywords - description
		 *========================================*/
		$title = Zendvn_Filter_Filter::filterContent($this->view->Item['name'], 'filter');
		$option['keywords'] = Zendvn_Filter_Filter::filterContent($this->view->Item['html_keyword'], 'filter');
		
		$html_description 	= Zendvn_Filter_Filter::filterContent($this->view->Item['html_descript'], 'filter');
		$article_content 	= Zendvn_Filter_Filter::filterContent(trim(strip_tags($this->view->Item['content'])), 'filter');
		$article_content 	= Zendvn_Filter_Filter::shortString($article_content, 200);
		
		$description		= empty($html_description)?$article_content:$html_description;
		
		$option['description'] = $description;
		$this->setTitle($title, $option);
		
	}
	
	public function aboutUsAction(){
		$tblItem = new Zendvn_Model_Table_PageContent();
		$this->view->Item = $tblItem->getItem(array('page' => 'about-us'), array('task' => 'base-alias'));
		
		/*========================================
		 * Set meta title - keywords - description
		*========================================*/
		$title = Zendvn_Filter_Filter::filterContent($this->view->Item['name'], 'filter');
		$option['keywords'] = Zendvn_Filter_Filter::filterContent($this->view->Item['html_keyword'], 'filter');
		$option['description'] = Zendvn_Filter_Filter::filterContent($this->view->Item['html_descript'], 'filter');
		$this->setTitle($title, $option);
	}
	
	public function recruitmentAction(){
		$tblItem = new Zendvn_Model_Table_PageContent();
		$this->view->Item = $tblItem->getItem(array('page' => 'recruitment'), array('task' => 'base-alias'));
		
		/*========================================
		 * Set meta title - keywords - description
		*========================================*/
		$title = Zendvn_Filter_Filter::filterContent($this->view->Item['name'], 'filter');
		$option['keywords'] = Zendvn_Filter_Filter::filterContent($this->view->Item['html_keyword'], 'filter');
		$option['description'] = Zendvn_Filter_Filter::filterContent($this->view->Item['html_descript'], 'filter');
		$this->setTitle($title, $option);
	}
	
	public function browseAction(){
		if(!empty($this->_arrParam['alias'])){
			$tblItem = new Zendvn_Model_Table_PageContent();
			$this->view->Item = $tblItem->getItem(array('page' => $this->_arrParam['alias']), array('task' => 'base-alias'));
		
			/*========================================
			 * Set meta title - keywords - description
			*========================================*/
			$title = Zendvn_Filter_Filter::filterContent($this->view->Item['name'], 'filter');
			$option['keywords'] = Zendvn_Filter_Filter::filterContent($this->view->Item['html_keyword'], 'filter');
			$option['description'] = Zendvn_Filter_Filter::filterContent($this->view->Item['html_descript'], 'filter');
			$this->setTitle($title, $option);
		}
	}

	
	public function contactAction(){
		$captcha = new Zendvn_Captcha_Image(array(
												'width' => 184,
												'height' => 57,
												'wordlen' => 4
												));
												
		$this->view->captcha = $captcha->render($this->view);
		$this->view->captcha_id = $captcha->getId();
		
		if($this->_request->isPost()){
			$validator = new Default_Form_ValidateContact($this->_arrParam);
			if($validator->isError()){
				$this->view->errors = $validator->getMessageError();
				$this->view->Item = $validator->getData();
			}else{
				$data = $validator->getData();
				$mail = new Zendvn_Mail();
				$result = $mail->sendContact($data);
				if($result){
					$this->_helper->flashMessenger->addMessage('Cảm ơn bạn đã gửi thông tin đến cho chúng tôi!');
				}else{
					$this->_helper->flashMessenger->addMessage('Error! Can not send!');
				}
				$this->_redirect($this->_currentController . '/contact');
			}
		}
		$this->view->messages = $this->_helper->flashMessenger->getMessages();
	}
	
	public function captchaImageAction(){
		$this->_helper->layout->disableLayout();
		$captcha = new Zendvn_Captcha_Image(array('width' => 184, 'height' => 57));
		$captchaID = $this->_request->getParam('captchaID',0);
		$captcha->removeCaptchaImg($captchaID);
	
		$this->view->captcha = $captcha->render($this->view);
		$this->view->captcha_id = $captcha->getId();
	}
	
	public function searchAction(){
		/*==============================
		 * List product of category
		 *==============================*/
		$tblItem = new Zendvn_Model_Table_Product();
		$this->view->Items = $tblItem->listItem($this->_arrParam, array('task' => 'search-product'));
		
		$totalItem = $tblItem->totalItem($this->_arrParam);
			
		$panigator = Zendvn_Paginator::create($this->_arrParam['panigator'],$totalItem);
		$this->view->panigator = $panigator;
		
		
	}
	public function filterProductAction(){
		/*==============================
		 * List product of category
		*==============================*/
		$tblItem = new Zendvn_Model_Table_Product();
		$this->view->Items = $tblItem->listItem($this->_arrParam, array('task' => 'filter-product-search'));
	
		$totalItem = $tblItem->totalItem($this->_arrParam);
			
		$panigator = Zendvn_Paginator::create($this->_arrParam['panigator'],$totalItem);
		$this->view->panigator = $panigator;
	
		/*========================================
		 * Set meta title - keywords - description
		*========================================*/
		$title = 'Danh sách sản phẩm';
		$this->setTitle($title);
		
		$this->view->headTitle = $title;
		$this->_helper->viewRenderer('product-category');
	}
	
	public function orderAction(){
		if(!empty($this->_arrParam['product_id'])){
			$tblSize 					= new Zendvn_Model_Table_ProductSize();
			$this->view->slbSize 		= $tblSize->itemInSelect($this->_arrParam, array('task' => 'get-select'));
			
			$tblColor 					= new Zendvn_Model_Table_ProductColor();
			$this->view->slbColor 		= $tblColor->itemInSelect($this->_arrParam, array('task' => 'get-select'));
			
			$tblItem 					= new Zendvn_Model_Table_Product();
			$this->view->Item 			= $tblItem->getItem(array('id' => $this->_arrParam['product_id']), array('task' => 'info'));
			
			if($this->_request->isPost()){
				$yourCart 		= new Zend_Session_Namespace('cart');
				$yourCart->setExpirationSeconds(3600);
				$carInfo 		= $yourCart->getIterator();
				$arrCartInfo 	= $carInfo['cart']; 
				$flag_cart		= '';
				$key_update		= 0;
				$tblItem		= new Zendvn_Model_Table_Product();
				$productInfo 	= $tblItem->getItem(array('id' => $this->_arrParam['product_id']));

				$arrPrice		= @json_decode($productInfo['stock'], true);
				
				if(!empty($arrCartInfo)){
					foreach ($arrCartInfo as $k => $v){
						if($arrCartInfo[$k]['id'] == $this->_arrParam['product_id']){
							if($arrCartInfo[$k]['size'] == $this->_arrParam['hidden_size']){
								if($arrCartInfo[$k]['color'] == $this->_arrParam['hidden_color']){
									$yourCart->cart[$k]['quantity'] += $this->_arrParam['quantity'];
									$flag_cart = '';
									break;
								}else{
									$flag_cart = 'add-new';
								}
							}else{
								$flag_cart = 'add-new';
							}
						}else{
							$flag_cart = 'add-new';
						}
					}
				}else{
					$flag_cart = 'add-new';
				}
				
				if($flag_cart == 'add-new'){
					$arrCart = array();
					$newPrice 	= (empty($productInfo['sale_price']) || $productInfo['sale_price'] == 0)?$productInfo['price']:$productInfo['sale_price'];
					$arrCart = array(
							'id' => $this->_arrParam['product_id'],
							'size' => $this->_arrParam['hidden_size'],
							'color' => $this->_arrParam['hidden_color'],
							'quantity' => $this->_arrParam['quantity'],
							'price' => $newPrice
					);
					$yourCart->cart[] = $arrCart;
				}
				
				
				$carInfo 		= $yourCart->getIterator();
				
				
				
				
				
				$this->_helper->viewRenderer->setNoRender();	
			}
		}
		$this->_helper->layout->disableLayout();
	}
	
	public function getColorAction(){
		if(!empty($this->_arrParam['product_id']) && !empty($this->_arrParam['size_id'])){
			$tblColor 	= new Zendvn_Model_Table_ProductColor();
			$this->view->colorData 	= $tblColor->itemInSelect($this->_arrParam, array('task' => 'get-select'));
			
			$tblItem 	= new Zendvn_Model_Table_Product();
			$itemInfo 	= $tblItem->getItem(array('id' => $this->_arrParam['product_id']));
			$arrColor	= @json_decode($itemInfo['color'], true);
			$arrStock	= @json_decode($itemInfo['stock'], true);
			
			$this->view->arrStock 	= $arrStock[$this->_arrParam['size_id']];
			$this->view->arrColor	= $arrColor[$this->_arrParam['size_id']];
		}
		$this->_helper->layout->disableLayout();
		
	}
	
	public function processCartAction(){
		$yourCart = new Zend_Session_Namespace('cart');
		$carInfo = $yourCart->getIterator();
		$arrCart = $carInfo['cart'];
		if($this->_arrParam['type'] == 'decrease'){
			$key = $this->_arrParam['key'];
			if($yourCart->cart[$key]['quantity'] - 1 == 0){
				$arrResponse = array('type' => 'minimum');
			}else{
				$yourCart->cart[$key]['quantity'] = $yourCart->cart[$key]['quantity'] - 1;
				
				$totalPriceItem = $yourCart->cart[$key]['quantity'] * $yourCart->cart[$key]['price'];
				$totalPrice = $this->_arrParam['totalPrice'] - $yourCart->cart[$key]['price'];
				
				$arrResponse = array(
								'type' => 'success',
								'quantity' => $yourCart->cart[$key]['quantity'],
								'totalPriceItem' => number_format($totalPriceItem), 
								'totalPrice' => number_format($totalPrice),
								'hiddenTotal' => $totalPrice
								);
					
			}
				echo json_encode($arrResponse);
		}
		
		if($this->_arrParam['type'] == 'increase'){
			$key = $this->_arrParam['key'];
			
			$tblItem = new Zendvn_Model_Table_Product();
			$productInfo = $tblItem->getItem(array('id' => $yourCart->cart[$key]['id']));
			
			$arrStock = @json_decode($productInfo['stock'], true);
			
			$maxQuantity = $arrStock[$yourCart->cart[$key]['size']][$yourCart->cart[$key]['color']];
			
			if($yourCart->cart[$key]['quantity'] + 1 > $maxQuantity){
				$arrResponse = array('type' => 'maximum');
			}else{
				$yourCart->cart[$key]['quantity'] = $yourCart->cart[$key]['quantity'] + 1;
					
				$totalPriceItem = $yourCart->cart[$key]['quantity'] * $yourCart->cart[$key]['price'];
				$totalPrice = $this->_arrParam['totalPrice'] + $yourCart->cart[$key]['price'];
					
				$arrResponse = array(
								'type' => 'success',
								'quantity' => $yourCart->cart[$key]['quantity'],
								'totalPriceItem' => number_format($totalPriceItem), 
								'totalPrice' => number_format($totalPrice),
								'hiddenTotal' => $totalPrice
							);
			}
				
			echo json_encode($arrResponse);
		}
		
		if($this->_arrParam['type'] == 'delete'){
			$key = $this->_arrParam['key'];
			
			$totalPrice = $this->_arrParam['totalPrice'] - ($yourCart->cart[$key]['price'] * $yourCart->cart[$key]['quantity']);
			$arrResponse = array(
					'type' => 'success',
					'totalPrice' => number_format($totalPrice),
					'hiddenTotal' => $totalPrice
			);
			unset($yourCart->cart[$key]);
			echo json_encode($arrResponse);
		}
		
		if($this->_arrParam['type'] == 'submit'){
			$yourCart->comment = $this->_arrParam['comment'];
		}
		
		$this->_helper->layout()->disableLayout();
		$this->_helper->viewRenderer->setNoRender();

	}
	
	public function cartAction(){
		$tblSize 					= new Zendvn_Model_Table_ProductSize();
		$this->view->slbSize 		= $tblSize->itemInSelect($this->_arrParam, array('task' => 'get-select'));
		
		$tblColor 					= new Zendvn_Model_Table_ProductColor();
		$this->view->slbColor 		= $tblColor->itemInSelect($this->_arrParam, array('task' => 'get-select'));
		
		$yourCart = new Zend_Session_Namespace('cart');
		$carInfo = $yourCart->getIterator();
		$arrCart = $carInfo['cart'];
		$arrIds	= array();
		if(!empty($arrCart)){
			foreach ($arrCart as $k => $v){
				$arrIds[] = $v['id'];
			}
			$arrIds = array_unique($arrIds);
			$this->view->arrCart = $arrCart;
		}
	}
	
	
	public function checkOutAction(){
		$tblSize 					= new Zendvn_Model_Table_ProductSize();
		$this->view->slbSize 		= $tblSize->itemInSelect($this->_arrParam, array('task' => 'get-select'));
		
		$tblColor 					= new Zendvn_Model_Table_ProductColor();
		$this->view->slbColor 		= $tblColor->itemInSelect($this->_arrParam, array('task' => 'get-select'));
		
		$yourCart = new Zend_Session_Namespace('cart');
		$carInfo = $yourCart->getIterator();
		$arrCart = $carInfo['cart'];
		$arrIds	= array();
		if(!empty($arrCart)){
			foreach ($arrCart as $k => $v){
				$arrIds[] = $v['id'];
			}
			$arrIds = array_unique($arrIds);
			$this->view->arrCart = $arrCart;
		}
		
		if($this->_request->isPost()){
			$validator = new Default_Form_ValidateCheckout($this->_arrParam);
			if($validator->isError()){
				$this->view->errors = $validator->getMessageError();
				$this->view->Item = $validator->getData();
			}else{
				$tblInvoice = new Zendvn_Model_Table_Invoice();
				$tblInvoiceDetail = new Zendvn_Model_Table_InvoiceDetail();
				
				$invoiceId = $tblInvoice->saveItem($this->_arrParam, array('task' => 'check-out'));
				foreach ($arrCart as $k => $v){
					$arrData = array(
									'product_id' => $v['id'],
									'invoice_id' => $invoiceId,
									'size' => $v['size'],
									'color' => $v['color'],
									'quantity' => $v['quantity'],
									'price' => $v['price'],
									);
					$tblInvoiceDetail->saveItem($arrData, array('task' => 'add-invoice'));
				}
				$yourCart->unsetAll();
//				$this->_helper->flashMessenger->addMessage('Cám ơn quý khách đã sử dụng dịch vụ của chúng tôi. Chúng tôi sẽ liên hệ với quý khác trong thời gian sớm nhất');
//				$this->view->messages = $this->_helper->flashMessenger->getMessages();
				
				$urlOptions = array('action'=>'view-order','id'=>$invoiceId);
				$name = '';
				$this->_helper->redirector->setGotoRoute($urlOptions, $name, true, false);
			}
		}
	}
	
	public function viewOrderAction(){
		$tblSize 					= new Zendvn_Model_Table_ProductSize();
		$this->view->slbSize 		= $tblSize->itemInSelect($this->_arrParam, array('task' => 'get-select'));
		
		$tblColor 					= new Zendvn_Model_Table_ProductColor();
		$this->view->slbColor 		= $tblColor->itemInSelect($this->_arrParam, array('task' => 'get-select'));
		
		
		$tblInvoice = new Zendvn_Model_Table_Invoice();
		$this->view->invoiceDetail = $tblInvoice->getItem($this->_arrParam);
		
		$tblInvoiceDetail = new Zendvn_Model_Table_InvoiceDetail();
		$result = $tblInvoiceDetail->listItem(array('invoice_id' => $this->view->invoiceDetail['id']), array('task' => 'view-order'));
		if(!empty($result)){
			foreach ($result as $k => $v){
				$result[$k]['id'] = $v['product_id'];
			}
		}
		$this->view->arrCart = $result;
	}
	
	public function testAction(){
		$yourCart = new Zend_Session_Namespace('cart');
		$yourCart->setExpirationSeconds(3600);
// 		$yourCart->unsetAll();
		$carInfo = $yourCart->getIterator();
		echo '<pre>';
		print_r($carInfo);
		echo '</pre>';
	}
	
	function searchValue($value, $key, $arrData){
		$flag = false;
		if(!empty($arrData)){
			foreach ($arrData as $k => $v){
				foreach ($arrData[$k] as $ke => $va){
					if($value == $arrData[$k][$key]){
						$flag = $k;
					}
				}
			}
		}
		return $flag;
	}

}